<template>
    <view>
        <!-- <navigation-bar :back="false" title="发布圈子"></navigation-bar> -->
        <navigation-bar :back="false" title="发布帖子"></navigation-bar>

        <view class="push">
            <view class="push1">
                <view class="push2">提醒</view>
                <view class="push3">禁止发布任何非法及与游戏无关的内容</view>
            </view>
            <view class="push4">
                <view class="push5">标题</view>
                <view class="push6">{{ text1.length }}/50</view>
            </view>
            <view class="push7">
                <input class="push8" placeholder="醒目的标题" @input="onChange1" :value="text1" />
            </view>
            <view class="push4">
                <view class="push5">内容</view>
                <view class="push6">{{ text2.length }}/2000</view>
            </view>
            <view class="push9">
                <textarea class="push10" placeholder="游戏体验推荐心得" @input="onChange2"  maxlength="2000" :value="text2"></textarea>
                <view style="display: flex; flex-wrap: wrap; gap: 15rpx">
                    <view style="position: relative" v-for="(item, index) in uploadImageData" :key="index">
                        <view class="upImg1"><image :src="item" style="width: 100%; height: 100%"></image></view>

                        <view @tap="deleteImg" :data-data="index" class="upImg4">×</view>
                    </view>
                    <view class="upImg1" @tap="uploadImage">
                        <view class="upImg2">+</view>
                        <view class="upImg3">上传图片</view>
                    </view>
                </view>
            </view>

            <view class="push4">
                <view class="push5">自定义标签</view>
                <view class="push6">{{ text3.length }}/6</view>
            </view>
            <view class="push7">
                <input class="push8" placeholder="比如：休闲、轮子大作战" @input="onChange3" :value="text3" />
            </view>

            <view class="push4">
                <view class="push5">游戏名</view>
                <view class="push6">{{ text5.length }}/12</view>
            </view>
            <view class="push7">
                <input class="push8" placeholder="比如：休闲、轮子大作战" @input="onChange5" :value="text5" />
            </view>

            <view class="push4">
                <view class="push5">圈子分类</view>
            </view>
            <view class="push11">
                <view :class="typeIndex == '1' ? 'push13' : 'push12'" @tap="changeType" data-data="1">热游</view>
                <view :class="typeIndex == '2' ? 'push13' : 'push12'" @tap="changeType" data-data="2">新游</view>
                <view :class="typeIndex == '3' ? 'push13' : 'push12'" @tap="changeType" data-data="3">好游</view>
                <view :class="typeIndex == '4' ? 'push13' : 'push12'" @tap="changeType" data-data="4">吐槽</view>
            </view>

            <view class="push14" @tap="uploadForum">发布</view>

            <view style="display: flex; margin-left: 110rpx; margin-top: 40rpx; align-items: center">
                <checkbox-group @change="onChange4"><checkbox :checked="isAgree" /></checkbox-group>
                <view>
                    我同意
                    <span style="color: var(--Color)" @click="goToYinsi">《隐私协议》</span>
                    <span style="color: var(--Color)" @click="goToShouquan">《用户协议》</span>
                </view>
            </view>
        </view>
        <!-- 添加自定义登录提示框 -->
		<CustomConfirm
			:visible.sync="showLoginConfirm"
			title="温馨提示"
			content="亲，您还没登录，请先登录~"
			@confirm="handleLoginConfirm"
			@cancel="handleLoginCancel"
		/>
    </view>
</template>

<script>
import loginStatusUtils from '../../utils/loginStatusUtils';
import CustomConfirm from '../../components/CustomConfirm/CustomConfirm.vue'; 
import navigationBar from '../../components/navigation-bar/navigation-bar.vue';
import { url } from '../../config';
import { pushForum } from '../../api/getApi';
import userInfo from '../../store/userInfo';
import { updateMyViewTabBarText } from '../../utils/tabBarUtils';
export default {
    components: {
        navigationBar,
        CustomConfirm
    },
    data() {
        return {
            myGame: [],
            uploadImageData: [],
            typeIndex: '1',
            text1: '',
            text2: '',
            text3: '',
            text5: '',
            isAgree: false,
            showLoginConfirm: false,//登录提示框是否显示
            userData: userInfo.getUserInfo(),//用户数据
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad(options) {},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.userData = userInfo.getUserInfo();
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        updateMyViewTabBarText();
        let myGame = uni.getStorageSync('myGame');
        if (!myGame) {
            myGame = [];
        } else {
            myGame = JSON.parse(myGame).slice(0, 20);
        }
        this.setData({
            myGame: myGame
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        //登录提示框确认事件
		handleLoginConfirm() {
			uni.navigateTo({
				// 跳进登录页面
				url: '/pages/login/login'
			});
		},
		//登录提示框取消事件
		handleLoginCancel() {
			this.showLoginConfirm = false;
		},
        onChange1(e) {
            this.setData({
                text1: e.detail.value
            });
        },

        onChange2(e) {
            this.setData({
                text2: e.detail.value
            });
        },

        onChange3(e) {
            this.setData({
                text3: e.detail.value
            });
        },

        onChange4(e) {
            this.setData({
                isAgree: !this.isAgree
            });
        },

        onChange5(e) {
            this.setData({
                text5: e.detail.value
            });
        },

        deleteImg(e) {
            let data = this.uploadImageData.filter((_, index) => index !== e.target.dataset.data);
            this.setData({
                uploadImageData: data
            });
        },

        //上传图片
        uploadImage() {
            //检查登录状态
            if (!loginStatusUtils.checkLoginAndShowConfirm(this)) {
                return;
            }
            if (!this.isAgree) {
                uni.showToast({
                    title: '请先同意协议',
                    icon: 'none'
                });
                return;
            }
            if (this.checkFFGame()) {
                return;
            }
            uni.chooseImage({
                success: (res) => {
                    const tempFilePaths = res.tempFilePaths;
                    tempFilePaths.forEach((element) => {
                        uni.uploadFile({
                            url: url.baseUrl + '/sys/file/upload',
                            filePath: element,
                            name: 'file',
                            formData: {
                                openid: uni.getStorageSync('openId')
                            },
                            success: (res) => {
                                let result = JSON.parse(res.data);
                                if (result.data.errmsg == 'ok') {
                                    this.setData({
                                        uploadImageData: [result.data.url, ...this.uploadImageData]
                                    });
                                } else {
                                    uni.showToast({
                                        title: '禁止上传非法图片，如多次上传将永久封禁',
                                        icon: 'none'
                                    });
                                }
                                if (result.data.errmsg.includes('rid')) {
                                    let ffCount = uni.getStorageSync('ffCount') ? Number(uni.getStorageSync('ffCount')) : 0;
                                    ffCount = ffCount + 1;
                                    uni.setStorageSync('ffCount', ffCount);
                                }
                            },
                            fail(error) {
                                uni.showToast({
                                    title: '上传失败,请稍后重试',
                                    icon: 'none'
                                });
                            }
                        });
                    });
                }
            });
        },

        uploadForum() {
            // 检查登录状态
            if (!loginStatusUtils.checkLoginAndShowConfirm(this)) {
                return;
            }

            if (!this.isAgree) {
                uni.showToast({
                    title: '请先同意协议',
                    icon: 'none'
                });
                return;
            }
            
            // 使用 this.userData 而不是 userData
            // if (!this.userData) {
            //     uni.showToast({
            //         title: '未登录~',
            //         icon: 'none',
            //         duration: 2000
            //     });
            //     setTimeout(() => {
            //         uni.navigateTo({
            //             url: '/pages/login/login'
            //         });
            //     }, 2000);
            //     return;
            // }
            
            if (this.checkFFGame()) {
                return;
            }
            
            if (this.text1.length > 50 || this.text1.length == 0) {
                uni.showToast({
                    title: '标题长度不合法',
                    icon: 'none'
                });
                return;
            }
            if (this.text2.length > 2000 || this.text2.length == 0) {
                uni.showToast({
                    title: '内容长度不合法',
                    icon: 'none'
                });
                return;
            }
            /* if (this.text3.length > 6 || this.text3.length == 0) {
                uni.showToast({
                    title: '自定义标签长度不合法',
                    icon: 'none'
                });
                return;
            }
            if (this.text5.length > 12 || this.text5.length == 0) {
                uni.showToast({
                    title: '游戏名长度不合法',
                    icon: 'none'
                });
                return;
            } */
            

            /* const userData = uni.getStorageSync('userData');

            // 安全解析userData
            let userDataObj;
            try {
                userDataObj = JSON.parse(userData);
            } catch (e) {
                uni.showToast({
                    title: '用户数据异常，请重新登录',
                    icon: 'none'
                });
                return;
            } */

            
            let pushData = {
                // openid: uni.getStorageSync('openId'),微信号
                head: this.userData.avatarUrl,//用户头像
                name: this.userData.name,//用户昵称
                title: this.text1,//标题
                content: this.text2,//内容
                tag1: this.typeIndex == '1' ? '热游' : this.typeIndex == '2' ? '新游' : this.typeIndex == '3' ? '好游' : '吐槽',//圈子分类
                tag2: this.text3,//自定义标签
                gamename: this.text5,//游戏名
                type: this.typeIndex,//圈子分类
                image: this.uploadImageData.join(','),//图片列表
                creator: this.userData.id//创建用户id
            };
            
            pushForum(pushData).then((res) => {
                console.log(res);
                if(res.code==0&&res.data === '发布成功') {
                    uni.showToast({
                        title: '发布成功',
                        icon: 'none'
                    });
                    this.setData({
                        uploadImageData: [],
                        text1: '',
                        text2: '',
                        text3: '',
                        text5: ''
                    });
                }
                else if (res != '标题/内容/标签存在非法信息，如若再犯将永久封禁') {
					uni.showToast({
						title: "您提交的信息包含"+JSON.parse(res.data)["检测结果"]+"内容，在此提醒您遵守协议政策，网络不是法外之地",
						icon: 'none'
					});
					this.setData({
                        uploadImageData: [],
                        text1: '',
                        text2: '',
                        text3: '',
                        text5: ''
                    });
                } else {
                    let ffCount = uni.getStorageSync('ffCount') ? Number(uni.getStorageSync('ffCount')) : 0;
                    ffCount = ffCount + 1;
                    uni.setStorageSync('ffCount', ffCount);
                }
            });
        },

        checkFFGame() {
            let ffCount = uni.getStorageSync('ffCount') ? Number(uni.getStorageSync('ffCount')) : 0;
            if (ffCount > 10) {
                uni.showModal({
                    title: '提示',
                    content: '你因为多次恶意非法上传，已被禁止发布'
                });
                return true;
            }
            if (ffCount > this.myGame.length) {
                uni.showModal({
                    title: '提示',
                    content: '你因多次尝试上传非法内容，为防止恶意上传，你还需要再玩 ' + (ffCount - this.myGame.length) + ' 款不同的游戏后才可继续上传发布'
                });
                return true;
            }
            return false;
        },

        changeType(event) {
            this.setData({
                typeIndex: event.target.dataset.data
            });
        },

        goToYinsi() {
            uni.navigateTo({
                url: '/pages/yinsi/yinsi'
            });
        },

        goToShouquan() {
            uni.navigateTo({
                url: '/pages/yonghu/yonghu'
            });
        }
    }
};
</script>
<style>
.push {
    padding: 30rpx;
}

.push1 {
    display: flex;
    background: black;
    height: 58rpx;
    align-items: center;
    padding: 0 20rpx;
    border-radius: 10rpx;
}

.push2 {
    color: black;
    background: white;
    padding: 0 10rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
}

.push3 {
    color: white;
}

.push4 {
    display: flex;
    justify-content: space-between;
    margin: 20rpx 0;
    margin-top: 30rpx;
}

.push5 {
    font-weight: bold;
    font-size: 30rpx;
}

.push6 {
    font-size: 25rpx;
    color: gray;
}

.push8 {
    border-bottom: 1rpx solid #dadada;
    padding-bottom: 10rpx;
}

.push10 {
    width: 100%;
    background: #f3f3f3;
    border-radius: 10rpx;
}

.push11 {
    display: flex;
    align-items: center;
}

.push12 {
    background: #ededed;
    border-radius: 10rpx;
    width: max-content;
    padding: 13rpx 28rpx;
    color: black;
    font-size: 24rpx;
    margin: 0 18rpx 18rpx 0;
}

.push13 {
    border-radius: 10rpx;
    width: max-content;
    padding: 11rpx 26rpx;
    font-size: 24rpx;
    margin: 0 18rpx 18rpx 0;
    border: 2rpx solid var(--LColor50);
    color: var(--Color);
    background: var(--LColor20);
}

.push14 {
    border-radius: 100rpx;
    width: auto;
    padding: 18rpx 26rpx;
    font-size: 24rpx;
    border: 2rpx solid var(--LColor50);
    color: var(--Color);
    background: var(--LColor20);
    text-align: center;
    margin-top: 60rpx;
}

.upImg1 {
    width: 160rpx;
    height: 160rpx;
    background: #eaeaea;
    border-radius: 10rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.upImg2 {
    font-size: 55rpx;
    color: gray;
}

.upImg3 {
    font-size: 22rpx;
    color: gray;
}

.upImg4 {
    position: absolute;
    top: 0;
    right: 0;
    background: black;
    width: 40rpx;
    height: 40rpx;
    border-radius: 100%;
    color: white;
    text-align: center;
    line-height: 35rpx;
    font-size: 40rpx;
    z-index: 99;
}
</style>
